<!--
 * @Author: your name
 * @Date: 2021-01-11 20:02:50
 * @LastEditTime: 2021-01-14 09:23:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \heima-mobileCP\src\views\Login\index.vue
-->
<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar title="黑马头条-登陆" />
    <!-- 表单部分 -->
    <van-form ref="form">
      <van-field v-model="mobile"
                 label="手机号"
                 placeholder="请输入手机号"
                 :rules="[{validator:validatorForMobile,message:'请输入正确的手机号且手机号必须是11位',trigger:'onBlur'}]" />
      <van-field v-model="code"
                 label="密码"
                 placeholder="请输入密码号"
                 :rules="[{required:true,message:'密码不能为空',trigger:'onBlur'}]" />
    </van-form>
    <!-- 登陆按钮 -->
    <div class="btn-wrap">
      <van-button type="info"
                  class="btn"
                  @click="doValidata">登陆</van-button>
    </div>
  </div>
</template>

<script>
import { login, getUserInfo } from '@/api/user'
export default {
  data () {
    return {
      mobile: '13211111111',
      code: '246810'
    }
  },
  methods: {
    // 手机号校验
    validatorForMobile (val) {
      return /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(val)
    },
    // 登录功能
    lLogin () {
      const data = {
        mobile: this.mobile,
        code: this.code
      }
      login(data).then((res) => {
        console.log(res)
        // 提交mutation将返回的token信息赋值到vuex中的tokenInfo上
        // $store 映射的方式
        this.$store.commit('setToken', res.data.data)
        // 调用用户信息接口
        getUserInfo()
        this.$router.push({
          path: '/'
        })
      })
    },
    // 兜底校验
    doValidata () {
      this.$refs.form.validate().then(() => {
        // 通过校验，调用登录接口
        this.lLogin()
      }).catch(() => {
        // 验证失败的操作
      })
    }
  }
}
</script>
<style lang="less">
.login {
  .btn-wrap {
    padding: 20px;
    .btn {
      width: 100%;
      background-color: #6db4fb;
      color: #fff;
    }
  }
}
</style>
